package com.wxw.BaseLibrary.tool;

/**
 *
 * @author david
 * @date 2014-09-02
 */
public class Timeout {
    private int time = 120;
    private int count = 0;
    private boolean stop = false;
    private OnTimeoutListener onTimeoutListener;

    public int getTime() {
        return time;
    }

    public Timeout setOnTimeoutListener(OnTimeoutListener onTimeoutListener) {
        this.onTimeoutListener = onTimeoutListener;
        return this;
    }

    /**
     * 等待多少秒
     * @param time
     */
    public Timeout(int time){
        this.time = time;
    }

    public void start() {
        count = time;
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (count>0 && !stop){
                    try {
                        Thread.sleep(1000);
                    } catch (Exception e) {

                    }
                    count--;
                }
                if (onTimeoutListener!=null && count==0) {
                    onTimeoutListener.onTimeout(this, time);
                }
            }
        }).start();
    }

    public void stop() {
        stop = true;
    }

    public interface OnTimeoutListener{
        /**
         * 超时事件
         * @param sender
         * @param time
         */
        void onTimeout(Object sender, int time);
    }
}
